<template>
  <view class="page">
    <!-- 头像预览 -->
    <view class="avatar-box">
      <image
        v-if="tempAvatar"
        :src="tempAvatar"
        mode="aspectFill"
        class="avatar-preview"
      />
      <image
        v-else-if="userInfo.user.avatar"
        :src="userInfo.user.avatar"
        mode="aspectFill"
        class="avatar-preview"
      />
      <view v-else class="avatar-placeholder">
        <uni-icons type="person-filled" size="60" color="#1E90FF" />
      </view>
    </view>

    <!-- 按钮组 -->
    <view class="btn-group">
      <button type="primary" class="btn" @tap="chooseImage">选择头像</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {}, // 当前用户信息
      tempAvatar: "", // 临时预览地址
    };
  },
  onLoad() {
    // 获取用户信息（含头像）
    this.getUserInfo();
  },
  methods: {
    back() {
      uni.navigateBack();
    },
    async getUserInfo() {
      const res = await uni.$http.get("/sys/user/info");
      this.userInfo = res.data.data;
    },
    // 上传头像（选择后立即上传）
    async chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: async (res) => {
          const tempPath = res.tempFilePaths[0];
          uni.showLoading({ title: "上传中..." });

          try {
            // 上传文件
            const uploadRes = await uni.uploadFile({
              url: `${uni.$baseUrl}/file/upload`, // 你的接口
              filePath: tempPath,
              name: "file", // 必须和 @RequestParam("file") 一致
              header: {
                Authorization: uni.getStorageSync("authorization"), // 携带 token
              },
            });

            const data = JSON.parse(uploadRes[1].data);

            // 后端返回的是文件名，拼成完整地址
            // 假设你静态资源映射到 /avatar/
            const avatarUrl = `${uni.$baseUrl}/file/download?name=${data.message}`;
            this.tempAvatar = avatarUrl; // 预览用
            // 修改用户信息

            const u = {
              id: this.userInfo.user.id,
              avatar: avatarUrl,
            };
            console.log(u);

            const res = await uni.$http.put("/sys/user/updateAv", u);
            console.log(res);
          } catch (e) {
            uni.showToast({ title: "网络错误", icon: "none" });
          } finally {
            uni.hideLoading();
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-box {
  margin-top: 60rpx;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.avatar-preview {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #e6f3ff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-group {
  margin-top: 80rpx;
  width: 80%;
}

.btn {
  margin-bottom: 30rpx;
  background-color: #1e90ff;
  color: #fff;
  font-size: 32rpx;
  line-height: 90rpx;
  border-radius: 16rpx;
}

.btn-upload {
  background-color: #1e90ff;
  opacity: 0.8;
}

.btn-upload[disabled] {
  background-color: #ccc;
  color: #fff;
}
</style>
